﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PressureTest
{
    internal class Tool
    {
        /// <summary>十六进制字符串转byte
        /// 
        /// </summary>
        /// <param name="hs"></param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(string hs)
        {
            string a = hs.Replace(" ", "");
            int bytelength = 0;
            if (a.Length % 2 == 0)
            {
                bytelength = a.Length / 2;
            }
            else
            {
                bytelength = a.Length / 2 + 1;
            }
            byte[] b = new byte[bytelength];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < bytelength; i++)
            {
                if (i == bytelength - 1)
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2), 16);
                }
                else
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
                }
            }
            //按照指定编码将字节数组变为字符串
            return b;
        }

        /// <summary>字符串转GB2312
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string GetHexFromChs(string s)
        {
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
            byte[] bytes = chs.GetBytes(s);
            StringBuilder Text = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                Text.Append(string.Format("{0:X}", bytes[i]));
                //Text.Append(" ");
            }

            string ggg = Text.ToString();
            string ggf = ggg.Substring(ggg.Length - 1, 1);
            if (ggf == " ")
            {
                ggg = ggg.Remove(ggg.Length - 1, 1);
            }
            return ggg;
        }

        /// <summary>字符串字节长度
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int StringByteLength(string str)
        {
            if (str.Equals(string.Empty))
                return 0;
            int strlen = 0;
            ASCIIEncoding strData = new ASCIIEncoding();
            //将字符串转换为ASCII编码的字节数字
            byte[] strBytes = strData.GetBytes(str);
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都将编码为ASCII编码63,即"?"号
                    strlen++;
                strlen++;
            }
            return strlen;
        }

        /// Modbus CRC16校验计算
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static String CRCForModbus(String data)
        {
            //处理数字转换
            String sendBuf = data;
            String sendnoNull1 = sendBuf.Trim();//去掉字符串前后的空格
            String sendnoNull2 = sendnoNull1.Replace(" ", "");//去掉字符串中间的空格
            String sendNOComma = sendnoNull2.Replace(',', ' ');    //去掉英文逗号
            String sendNOComma1 = sendNOComma.Replace('，', ' '); //去掉中文逗号
            String strSendNoComma2 = sendNOComma1.Replace("0x", "");   //去掉0x
            data = strSendNoComma2.Replace("0X", "");   //去掉0X

            Byte[] crcbuf = hexStringToByteArray(data);

            //计算并填写CRC校验码
            Int32 crc = 0xffff;
            Int32 len = crcbuf.Length;
            for (Int32 n = 0; n < len; n++)
            {
                Byte i;
                crc = crc ^ crcbuf[n];
                for (i = 0; i < 8; i++)
                {
                    Int32 TT;
                    TT = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (TT == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            crc = ((crc & 0xFF) << 8 | (crc >> 8));//高低字节换位
            String CRCString = crc.ToString("X2");
            if (CRCString.Length % 2 != 0)
            {
                CRCString = "0" + CRCString;
            }
            return CRCString;
        }

        public static byte[] hexStringToByteArray(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                try
                {
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                }
                catch (System.FormatException)
                {
                }
            }
            return returnBytes;
        }
    }
}
